package com.zryc.shop.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zryc.shop.pms.entity.ProductCategory;
import com.zryc.shop.pms.mapper.ProductCategoryMapper;
import com.zryc.shop.pms.service.IProductCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 产品分类 服务实现类
 * </p>
 *
 * @author LiYe
 * @since 2023-02-09
 */
@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory> implements IProductCategoryService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public List listWithChildren() {
        List categoryList = null;
        String proCateTreeKey = "PRODUCT_CATEGORY_TREE_KEY";
        if (redisTemplate.hasKey(proCateTreeKey)) {
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~在Redis中找到了商品类别树，直接返回~~~~~~~~~~~~~~~~~~~~~~~~~");
            categoryList = redisTemplate.opsForList().range(proCateTreeKey, 0, -1);
            redisTemplate.expire(proCateTreeKey, 10, TimeUnit.MINUTES);//10分钟后过期
        } else {
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~查询MySQL数据库，得到商品类别树，更新Redis缓存~~~~~~~~~~~~~~~~~~~~~~~~~");
            QueryWrapper<ProductCategory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("level", 0);//先查询商品的1级分类
            queryWrapper.eq("show_status", 1);
            categoryList = this.list(queryWrapper);
            for (Object obj:categoryList) {
                ProductCategory parent = (ProductCategory) obj;
                //根据父类别ID，查询其子类别
                queryWrapper.clear();
                queryWrapper.eq("parent_id", parent.getId());
                queryWrapper.eq("show_status", 1);
                parent.setChildren(this.list(queryWrapper));
            }
            redisTemplate.opsForList().rightPushAll(proCateTreeKey, categoryList);//将查询到的最新的商品类别树写入Redis数据库
        }

        return categoryList;
    }
}
